package top.codedance.iotp.slave.service.slave;

import top.codedance.iotp.slave.bean.SlaveConnectParam;
import top.codedance.iotp.common.util.StringUtils;
import top.codedance.iotp.slave.SlaveApplication;
import org.apache.log4j.Logger;

import java.lang.reflect.Constructor;

public abstract class AbstractSlave implements Slave {
    private static Logger logger = SlaveApplication.getLogger(AbstractSlave.class);
    protected SlaveConnectParam param;
    protected static String type = "Serial";
    protected static final String pkg = "top.codedance.iotp.slave.service.slave";

    public AbstractSlave(SlaveConnectParam scp){
        this.param = scp;
    }

    @Override
    public void run() {
        init();
    }

    public static Slave getInstance(SlaveConnectParam scp){
        Slave s = null;
        type = StringUtils.firstCharToUperCase(scp.getType());
        String clazzType = pkg + "." + type + "Slave";
        try {
            Constructor<?> constructor = Class.forName(clazzType).getConstructor(SlaveConnectParam.class);
            s = (Slave)constructor.newInstance(scp);
        }catch (Exception e){
            logger.info("Slave port is init fail, system is shutdown.");
            System.exit(0);
        }

        return s;
    }

    /**
     * 发送数据
     * @param data
     */
    public abstract void send(byte[] data);

    public abstract void init();

    public abstract void destory();
}
